package dao

import (
	"context"
	"sale-admin/internal/dal"
	"sale-admin/internal/models"
	"strings"
	"time"

	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type OrderPoints struct{}

func (op OrderPoints) Create(ctx context.Context, db *gorm.DB, salesID, outTradeNo, openID string, Type int, pointsID string, points float64) (err error) {
	m := dal.Use(db).MaOrderPoints
	tx := m.WithContext(ctx)

	var PointsData models.MaOrderPoints
	PointsData.ID, _ = helper.UUID{}.String()
	PointsData.SalesID = salesID
	PointsData.OutTradeNo = outTradeNo
	PointsData.OpenID = openID
	PointsData.Type = Type
	PointsData.PointsID = pointsID
	PointsData.Points = points
	PointsData.CreatedAt = time.Now().Unix()

	tx.Create(&PointsData)
	return
}

func (op OrderPoints) Detail(ctx context.Context, db *gorm.DB, outTradeNo string, Type int) (res *models.MaOrderPoints, err error) {
	m := dal.Use(db).MaOrderPoints
	tx := m.WithContext(ctx)
	if outTradeNo != "" {
		tx = tx.Where(m.OutTradeNo.Eq(outTradeNo))
	}
	if Type != 0 {
		tx = tx.Where(m.Type.Eq(Type))
	}
	res, err = tx.Take()
	return
}

func (op OrderPoints) List(ctx context.Context, db *gorm.DB, outTradeNo string, Type int) (res []*models.MaOrderPoints, err error) {
	m := dal.Use(db).MaOrderPoints
	tx := m.WithContext(ctx)
	if outTradeNo != "" {
		tx = tx.Where(m.OutTradeNo.In(strings.Split(outTradeNo, ",")...))
	}
	if Type != 0 {
		tx = tx.Where(m.Type.Eq(Type))
	}
	res, err = tx.Find()
	return
}
